package com.future.hedongjun.home.adapter;

import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.dl7.player.media.IjkPlayerView;
import com.future.baselib.entity.BaseResponse;
import com.future.baselib.http.HttpRequest;
import com.future.baselib.utils.ToastUtils;
import com.future.baselib.view.IosAlertDialog;
import com.future.hedongjun.R;
import com.future.hedongjun.common.MyApp;
import com.future.hedongjun.home.bean.ClassDetail;
import com.future.hedongjun.home.bean.ClassHourBean;
import com.future.hedongjun.home.bean.DanMuBean;
import com.future.hedongjun.home.bean.response.DanmuResponse;
import com.future.hedongjun.home.utils.DES;
import com.future.hedongjun.mine.order.ConfirmClassOrderActivity;
import com.kingsoft.media.httpcache.KSYProxyService;
import com.kingsoft.media.httpcache.OnCacheStatusListener;
import com.kingsoft.media.httpcache.OnErrorListener;

import java.io.File;
import java.util.List;

import static com.mob.MobSDK.getContext;

/**
 * 创建日期：2018/11/20 10:52
 * author liu.p.f
 * 类说明： 课时适配器
 */
public class ClassHourAdapter extends BaseQuickAdapter<ClassHourBean, BaseViewHolder> {
    private int mLastCheckedPosition = -1;
    private SparseBooleanArray mBooleanArray;
    private IjkPlayerView mIjkPlayer;
    private TextView tvDown;
    private TextView rvProgress;
    private List<ClassHourBean> mData;
    private List<DanMuBean> danMuBeans;
    private String classId;

    public ClassHourAdapter(@Nullable List<ClassHourBean> data, String id) {
        super(R.layout.recycler_item_class_hour, data);
        this.mData = data;
        this.classId = id;

    }

    @Override
    protected void convert(final BaseViewHolder helper, final ClassHourBean item) {
        helper.setText(R.id.tv_classTitle, item.title);
        tvDown.setVisibility(View.VISIBLE);
        if (mBooleanArray.get(helper.getAdapterPosition())) {
            helper.setTextColor(R.id.tv_classTitle, Color.parseColor("#CAD39B"));
            helper.setBackgroundRes(R.id.tv_classPause, R.drawable.yinping);
        } else {
            helper.setTextColor(R.id.tv_classTitle, Color.parseColor("#ff333333"));
            helper.setBackgroundRes(R.id.tv_classPause, R.drawable.kecheng_bofang_hui);
        }

        if (item.buy_status.equals("3")) {
            helper.setVisible(R.id.tv_classNoBuy, false);
            tvDown.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ToastUtils.longToast(mContext, "开始缓存");
                    KSYProxyService mProxyService = MyApp.getKSYProxy(mContext);
                    mProxyService.registerErrorListener(mOnErrorListener);
                    mProxyService.setMaxFilesCount(500);
                    mProxyService.setCacheRoot(new File(Environment.getExternalStorageDirectory().toString() + File.separator + "CacheFile" + "/" + "CacheVideo" + "/" + item.ClassName + "####" + item.classLogo));
                    mProxyService.startServer();
                    for (int i = 0; i < mData.size(); i++) {
                        mProxyService.startPreDownload(DES.decode(mData.get(i).address));
                        mProxyService.registerCacheStatusListener(mCacheStatusListener, DES.decode(mData.get(i).address));
                    }
                }
            });
        }

        helper.setOnClickListener(R.id.rl_hourItem, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (item.buy_status.equals("3")) {
                    setItemChecked(helper.getAdapterPosition());
                    mIjkPlayer.switchVideoPath(Uri.parse(DES.decode(item.address))).setTitle(item.title)    // set title
                            //.setSkipTip(0)  // set the position you want to skip
                            .enableOrientation()    // enable orientation
                            //.setVideoPath(VOD_URL)    // set video url
                            //.setVideoSource(null, VOD_URL, VOD_URL, VOD_URL, null) // set multiple video url
                            .setMediaQuality(IjkPlayerView.MEDIA_QUALITY_HIGH)  // set the initial video url
                            .enableDanmaku(true)  // enable Danmaku
                            // .setDanmakuSource(mContext.getResources().openRawResource(R.raw.bili))
                            .start(); // add Danmaku source, you need to use enableDanmaku() first
                    getDanmu();
                } else {
                    new IosAlertDialog(mContext)
                            .builder()
                            .setMsg("请先购买课程后,才能实用哟!")
                            .setNegativeButton("考虑一下", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {

                                }
                            })
                            .setPositiveButton("立即购买", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    if (mData != null) {
                                        ClassDetail detail = new ClassDetail();
                                        detail.setId(item.id);
                                        detail.setName(item.ClassName);
                                        detail.setLogo_img(item.classLogo);
                                        double price = 0;
                                        try {
                                            price = Double.valueOf(item.classPrice);
                                        } catch (NumberFormatException e) {

                                        }
                                        detail.setPrice(price);
                                        ConfirmClassOrderActivity.open(getContext(), detail);
                                    }
                                }
                            }).show();
                }
            }
        });
    }


    /**
     * @param position
     */
    public void setItemChecked(int position) {
        if (mLastCheckedPosition == position)
            return;

        mBooleanArray.put(position, true);

        if (mLastCheckedPosition > -1) {
            mBooleanArray.put(mLastCheckedPosition, false);
            notifyItemChanged(mLastCheckedPosition);
        }

        notifyDataSetChanged();
        mLastCheckedPosition = position;
    }

    public void setSelectData(SparseBooleanArray selectData, IjkPlayerView mIjkPlayer, TextView tvDown, TextView rvProgress) {
        this.mBooleanArray = selectData;
        this.mIjkPlayer = mIjkPlayer;
        this.tvDown = tvDown;
        this.rvProgress = rvProgress;
    }

    public int getPosition() {
        return mLastCheckedPosition;
    }

    private OnCacheStatusListener mCacheStatusListener = new OnCacheStatusListener() {
        @Override
        public void OnCacheStatus(String url, long sourceLength, int percentsAvailable) {
//            if (percentsAvailable == 100) {
//                rvProgress.setText("已缓存");
//            } else {
//                rvProgress.setText(percentsAvailable + "%");
//            }
            //ToastUtils.shortToast(mContext, percentsAvailable + "");
        }
    };

    private OnErrorListener mOnErrorListener = new OnErrorListener() {
        @Override
        public void OnError(int errCode) {
            Toast.makeText(mContext, "HttpCache meet an error:" + errCode, Toast.LENGTH_SHORT).show();
        }
    };


    private void getDanmu() {
        new HttpRequest<DanmuResponse>()
                .with(getContext())
                .setApiCode("_contentlist_001")
                .addParam("id", classId)
                .addParam("userToken", MyApp.getInstance().getUserToken())
                .addSuccessListener(new HttpRequest.OnNetworkSuccess() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        danMuBeans = ((DanmuResponse) response).data;
                        if (danMuBeans != null && danMuBeans.size() > 0) {
                            for (int i = 0; i < danMuBeans.size(); i++) {
                                mIjkPlayer.addDanmaku(danMuBeans.get(i).user_cotent, false);
                            }
                        }
                    }
                }).start(new DanmuResponse());
    }

}
